package com.livegoods.service;

import com.livegoods.pojo.Comment;
import com.livegoods.pojo.LivegoodsResult;
import com.livegoods.pojo.Order;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl  implements  CommentService{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public LivegoodsResult comment(String id, int page,int size) {

        Criteria criteria = Criteria.where("houseId").is(id);
        Query query = new Query(criteria);


        query.with(PageRequest.of(page,size));

        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        //将电话号码用正则替换4位位****
        for (Comment comment : comments) {
           comment.setUsername(comment.getUsername().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
        }



        GroupOperation groupOperation = Aggregation.group().count().as("total");

        TypedAggregation<Comment> commentTypedAggregation = new TypedAggregation<>(Comment.class, groupOperation);

        AggregationResults<Map> aggregate = mongoTemplate.aggregate(commentTypedAggregation, Map.class);

        Map uniqueMappedResult = aggregate.getUniqueMappedResult();

        //获取总数
        int total = (int) uniqueMappedResult.get("total");
        //计算总页数
        int totalPage = (int) Math.ceil(total/size);

        LivegoodsResult livegoodsResult = LivegoodsResult.ok(comments);
        //当前页小于总页数，还有下一页
        if(page+1<totalPage){
            livegoodsResult.setHasMore(true);
        }

        return livegoodsResult;
    }

    /**
     * 评论订单，通过订单id找到对应的房屋（最终评论的还是房屋）
     * @param orderId
     * @param feelback
     * @return
     */
    @Override
    public LivegoodsResult fellback(String orderId, String feelback) {

        try {
            Criteria criteria = Criteria.where("id").is(orderId);

            Query query = new Query(criteria);

            //1.查询订单信息
            Order order = mongoTemplate.findOne(query, Order.class);

            //2.创建评论对象
            Comment comment = new Comment();
            comment.setHouseId(order.getHouseId());
            comment.setUsername(order.getUser());
            comment.setStar(4);//前端没有提供，给个默认即可
            comment.setComment(feelback);

            //2.保存评论信息
            mongoTemplate.save(comment);

            //3.修改订单的
            Update commentStatus = Update.update("commentState", 2);
            UpdateResult updateResult = mongoTemplate.updateFirst(query, commentStatus, Order.class);
            LivegoodsResult ok = LivegoodsResult.ok();
            ok.setMsg("评论成功");
            return ok;
        } catch (Exception e) {
            e.printStackTrace();
            return LivegoodsResult.error("评论失败");
        }
    }
}
